<template>
  <div class="shop-cart">
    <van-cell
      :title="defaultAddr === '' ? '默认收货地址' : defaultAddr"
      is-link
      to="/addressList"
    />
    <div class="cards-list">
      <van-checkbox-group
        v-model="basketIds"
        ref="checkboxGroup"
        @change="checkedResultChange"
      >
        <div v-for="(item, index) in shopCartInfo" :key="index">
          <van-row
            v-for="items in item.shopCartItemDiscounts[0].shopCartItems"
            :key="items.basketId"
          >
            <van-col span="2">
              <van-checkbox
                @click.native="basketClick"
                :name="items.basketId"
              ></van-checkbox>
            </van-col>
            <van-col span="22">
              <text class="shop-name">{{ item.shopName }}</text>
              <van-card
                :num="items.prodCount"
                :price="items.price"
                :desc="items.skuName"
                :title="items.prodName"
                :thumb="items.pic"
              >
                <template #footer>
                  <van-stepper
                    v-model="items.prodCount"
                    async-change
                    @minus="minusThing(items)"
                    @plus="plusThing(items)"
                    integer
                  />
                </template>
              </van-card>
            </van-col>
          </van-row>
          <van-divider />
        </div>
      </van-checkbox-group>
      <van-empty v-if="shopCartInfo.value <= 0" />
      <van-submit-bar
        :price="totalMoney"
        button-text="提交订单"
        @submit="onSubmit"
      >
        <van-checkbox
          v-model="checkedAll"
          @change="allProdSelected"
          :indeterminate="isIndeterminate"
          >全选</van-checkbox
        >
        <a class="clear-cart" v-if="basketIds.length > 0" @click="clearCart"
          >清空</a
        >
      </van-submit-bar>
      <div style="height: 4rem"></div>
    </div>
  </div>
</template>

<script setup name="Login">
import { ref, reactive, onMounted, watch } from "vue";
import { shopCart, totalPay, changeItem, deleteItem } from "@/api/shopcart";
import { addressList1 } from "../api/address";
import { useRouter } from "vue-router";
let router = useRouter();
const checkboxGroup = ref(null);
let checkedAll = ref(false);
let shopCartInfo = ref([]);
let basketIds = reactive([]);
let totalMoney = ref(0);
let addresslist = reactive([]);
let defaultAddr = ref("");
let defaultAddrId = ref(0);
const isIndeterminate = ref(false);
let confirm = reactive({
  basketIds: [],
  orderItem: {
    prodId: 0,
    skuId: 0,
    prodCount: 1,
    shopId: 0,
    distributionCardNo: "",
  },
  addrId: 0,
  userChangeCoupon: 0,
  couponIds: [],
});
let changeItemList = reactive({
  basketId: 0,
  prodId: 0,
  skuId: 0,
  shopId: 0,
  count: 0,
  distributionCardNo: "",
});

onMounted(() => {
  shopMain();
  init();
});
// 获取商品信息
async function shopMain() {
  try {
    shopCartInfo.value = await shopCart({});
    console.log(shopCartInfo.value, "111111111111111");

    basketClick();
  } catch (err) {
    console.log(err, "err");
  }
}
// 获取地址信息
async function init() {
  addresslist = await addressList1();
  for (const key in addresslist) {
    if (Object.hasOwnProperty.call(addresslist, key)) {
      if (addresslist[key].commonAddr === 1) {
        const result = addresslist[key];
        defaultAddrId.value = addresslist[key].addrId;
        defaultAddr.value =
          result.province +
          " " +
          result.city +
          " " +
          result.area +
          " " +
          result.addr;
      }
    }
  }
}
// 提交订单
function onSubmit() {
  if (basketIds.length <= 0) return;
  confirm.basketIds = basketIds;
  confirm.addrId = defaultAddrId.value;
  sessionStorage.setItem("confirm", JSON.stringify(confirm));
  router.push("/order");
}
// 全选
function allProdSelected(event) {
  checkedAll.value = event;
  checkboxGroup.value.toggleAll(checkedAll.value);
  isIndeterminate.value = false;
  basketClick();
}
function checkedResultChange(value) {
  console.log(value, "value");
  const checkedCount = value.length;
  checkedAll.value =
    checkedCount ===
    shopCartInfo.value[0].shopCartItemDiscounts[0].shopCartItems.length;
  console.log(
    shopCartInfo.value[0].shopCartItemDiscounts[0].shopCartItems.length
  );
}
function clearCart() {
  deleteItem(basketIds).then((r) => {
    init();
    shopMain();
  });
}
function onStepperChange(items, value, callback) {
  changeItemList.basketId = items.basketId;
  changeItemList.prodId = items.prodId;
  changeItemList.skuId = items.skuId;
  changeItemList.shopId = items.shopId;
  changeItemList.count = value;
  changeItemList.distributionCardNo = "";
  changeItem(changeItemList).then((res) => {
    console.log(res, "eee");
  });
  callback();
}
// 减少
function minusThing(value) {
  let count = -1;
  onStepperChange(value, count, () => {
    basketClick();
  });
}
// 增加
function plusThing(value) {
  let count = 1;
  onStepperChange(value, count, () => {
    basketClick();
  });
}
// 计算总价
async function basketClick() {
  const result = await totalPay(basketIds);
  totalMoney.value = result.finalMoney * 100;
}
</script>
<style lang="scss" scoped>
.shop-cart {
  background-color: #fafafa;
  height: 100%;

  .clear-cart {
    margin-left: 1rem;
    color: #333;
  }

  .van-submit-bar {
    bottom: 3.2rem;
  }

  // .van-submit-bar {
  //   position: fixed;
  //   bottom: 0;
  //   left: 0;
  // }

  .cards-list {
    padding-right: 0.5rem;
    padding-left: 0.5rem;
    background-color: #fff;
    padding-bottom: 100rpx;

    .van-row {
      .van-col--2 {
        margin-top: 6rem;
      }

      .van-col {
        .shop-name {
          display: inline-block;
          height: 2.5rem;
          text-align: left;
          width: 100%;
          margin-top: 1rem;
          font-weight: 600;
        }

        .van-card {
          background-color: #fff;
        }
      }
    }
  }
}
</style>
